Ext.define('DCApp.view.doc.DataView', {
    extend: 'Ext.view.View',
    alias: 'widget.imageview',
    requires: [
                 'Ext.data.*',
                 'Ext.util.*',
                 'Ext.view.View',
                 'Ext.ux.DataView.DragSelector',
                 'Ext.ux.DataView.LabelEditor'
             ],   
    mixins: {
        dragSelector: 'Ext.ux.DataView.DragSelector',
        draggable   : 'Ext.ux.DataView.Draggable'
    },
    tpl: [
          '<tpl for=".">',
              '<div class="thumb-wrap" >',
           		'<div class="thumb" rel="fullScreenGallery" href="{uri_m}" style="background:url({uri}) 50% 50% no-repeat;"></div>',
                 '<span class="x-editable">{imageName:htmlEncode}</span>',
              '</div>',
          '</tpl>',
          '<div class="x-clear"></div>'
      ],
      cls: 'images-view',
      scrollable: false,
      trackOver: true,
      overItemCls: 'x-item-over',
      itemSelector: 'div.thumb-wrap',
      multiSelect: true,
    singleSelect: false,

      emptyText: 'No images to display',
      viewModel: {
          type: 'imagelist'
      },
      bind: {
          store: '{objs}'
      },
      detail_open:false,
	  listeners:{
		  itemupdate:function( rec, index, node, eOpts ){
			  //只在dataview下编辑label触发此逻辑，detail状态下不触发，点'保存'按钮才save,避免频繁调用rec.save
			 if(!rec.dirty || this.detail_open){
				 //rec.commit(true);
				 return;
			 }
				 
             rec.save({
                 scope: this,
                 callback: function(records,operation,success){
                	 if(success){
                         Ext.toast({
                             title: '保存',
                             html: '影像['+rec.getId()+']保存完成',
                             align: 't',
                             bodyPadding: 10
                         });
                	 }
                 }
             });
		  }
	  },
      refresh: function() {
    	  this.callParent(arguments);
    	  setTimeout(function(){    		  
    		  var fs =  $('.thumb[rel="fullScreenGallery"]');
    		  if(fs.length==0)
    			  return;
    		  fs.fullScreenGallery();   		  
    	  },200);
      },
      hookfullScreen:function(){
    	  setTimeout(function(){    		  
    		  var fs =  $('.thumb[rel="fullScreenGallery"]');
    		  if(fs.length==0)
    			  return;
    		  fs.fullScreenGallery();   		  
    	  },200);
      },
      afterRender: function() {
    	  //console.log(this);
    	  var v = this;
    	  v.dropZone = Ext.create("Ext.dd.DropZone",v.getEl(),{
    		    // Tell the zone what our target component is
    		    getTargetFromEvent: function(e) { 
    		        return e.getTarget(v.itemSelector);
    		    },
    		    // When the node is dropped, add a new instance to the
    		    // the component via the supplied component clone
    		    onNodeDrop : function(target,dd,e,data){
    		    	//前端界面拖拽及前端records更新
    		    	var rec = v.getRecord(target);
    		    	var datarecs = data.records;
                    var st = v.getStore();
                    var pos = st.indexOf(rec);
                    var pos1=st.indexOf(datarecs[0]);
                    if(pos==pos1)
                    	return false;
                    st.remove(datarecs);
                    //remove之后pos可能改变
                    pos = st.indexOf(rec);
                    st.insert(pos, datarecs);
                    
                    //通知服务端刷新，但前端并不刷新
                    var associatedProperty = v.dataSource.config.filters[0].property;
                    var associatedName = associatedProperty.substring(0, associatedProperty.length-2).toUpperCase();
                    var associatedID = v.dataSource.config.filters[0].value;
                    var relatedName = rec.store.model.entityName.toUpperCase();
                    var targetObj = rec.id;
                    var newOrder =[];
                    var recs= st.getData();
                    for(var i=0; i<recs.length; i++){
                    	newOrder.push(recs.items[i].getId());
                    }
                    //适应sim
                    if(!DCApp.Cfg.SIM_ENM['User'])
                      Ext.Ajax.request({
                        url: '/api/dragDropSort',
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        params : Ext.JSON.encode({'associatedName':associatedName,'associatedID':associatedID,'relatedName':relatedName,'targetObj':targetObj,'dragObj':newOrder}),
                        success: function(conn, response, options, eOpts) {
                        },
                        failure: function(conn, response, options, eOpts) {
                    
                        }
                    });
                    
                    v.hookfullScreen();
                },
    		    ddGroup: 'imgGroup'
    		  });
    	    this.callParent();
      },
    initComponent: function() {    
    	if(!DCApp.Cfg.bView){
            this.mixins.dragSelector.init(this);
            this.mixins.draggable.init(this, {
                ddConfig: {
                    ddGroup: 'imgGroup'
                },
                ghostTpl: [
                    '<tpl for=".">',
                        '<img src="{url}" />',
                        '<tpl if="xindex % 4 == 0"><br /></tpl>',
                    '</tpl>',
                    '<div class="count">',
                        '{[values.length]} images selected',
                    '<div>'
               ]
            });

    		Ext.apply(this,{  
    	      plugins: [
    	          Ext.create('Ext.ux.DataView.LabelEditor', {
    	        	  dataIndex: 'imageName'
    	          })
    	      ]
    		});            		
    	}
        
        this.callParent(arguments);
    }
});